import Index from '@/pages/frontend/index.vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import Login from "@/pages/admin/login.vue"
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
import articleList from '@/layouts/admin/article-list.vue'
import categoryList from '@/layouts/admin/category-list.vue'
import tagList from '@/layouts/admin/tag-list.vue'
import blogSetting from '@/layouts/admin/blog-setting.vue'

// 统一在这里声明所有路由
const routes = [
    {
        path: '/login', // 登录页
        component: Login,
        meta: {
            title: 'Weblog 登录页'
        }
    },
    {
        path: '/', // 路由地址
        component: Index, // 对应组件
        meta: { // meta 信息
            title: 'Weblog 首页' // 页面标题
        }
    }, {
        path: '/admin',
        component: import("@/layouts/admin/admin.vue"),
        meta: {
            title: 'Weblog 管理员首页'
        },
        redirect: '/admin/index',
        children: [
            {
                path: 'index',
                component: import("@/pages/admin/index.vue"),
               
            },
            {
                path: 'article-list',
                component: import("@/layouts/admin/article-list.vue"),
               
            },
            {
                path: 'category-list',
                component: import("@/layouts/admin/category-list.vue"),
               
            },
            {
                path: 'tag-list',
                component: import("@/layouts/admin/tag-list.vue"),
            },
            {
                path: 'blog-setting',
                component: import("@/layouts/admin/blog-setting.vue"),
            },
            
        ]
    }
]

// 创建路由
const router = createRouter({
    // 指定路由的历史管理方式，hash 模式指的是 URL 的路径是通过 hash 符号（#）进行标识
    history: createWebHashHistory(),
    // routes: routes 的缩写
    routes,
})
// 路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 排除login请求，如果不存在token直接跳转到login
    if (to.path !== '/login' && !userStore.getToken) {
        ElMessage.warning('请先登录')
        next('/login')
    } else if (to.path === '/login' && userStore.getToken) {
        ElMessage.warning('您已登录，请勿重复登录')
        next('/admin/index')
    } else {
        // 其他情况，正常放行
        next()
    }
})
// 全局路由后置守卫 配置网页的标签名
router.afterEach((to, from) => {
    // 动态设置页面 Title
    let title = (to.meta.title ? to.meta.title : '') + ' - Weblog'
    document.title = title
})
// ES6 模块导出语句，它用于将 router 对象导出，以便其他文件可以导入和使用这个对象
export default router
